#include "widget.h"
#include "ui_widget.h"
#include<Windows.h>
widget::widget()
    : QWidget()
    , ui(new Ui::widget)
{
    ui->setupUi(this);
}

widget::~widget()
{
    delete ui;
}

void widget::init(QTcpSocket*tso,QString account,QString name,QImage headimage,QString headimagepath,QString personalsign)
{
    //初始化数据库
    sd=QSqlDatabase::addDatabase("QSQLITE");
    sd.setDatabaseName("D:\\Qt6\\QtProject\\server\\server.db");
    sd.open();
    sq=new QSqlQuery(sd);

    //初始化个人信息
    Tso=tso;
    Account=account;
    Name=name;
    HeadImage=headimage;
    HeadImagePath=headimagepath;
    Personalsign=personalsign;
    ui->headimage->setIcon(QPixmap::fromImage(HeadImage));

    Ap=new addpeople;
    Ap->hide();
    nfl=new newfriendlist;
    nfl->hide();
    priinfo=new privateinfo;
    priinfo->init(Name,HeadImagePath,Personalsign,true);
    priinfo->hide();
    otherinfo=new privateinfo;
    otherinfo->hide();
    qDebug()<<"42";
    loaddata();
    ConnectSignal();
    qDebug()<<"4444";
    ui->meslist->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->peopleitemlist->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

void widget::ConnectSignal()
{
    connect(Ap,&addpeople::Searchpeople,this,[=](QString searchaccount){
        QJsonObject jo;
        jo.insert("datatype","searchpeople");
        jo.insert("account",searchaccount);
        QJsonDocument jd(jo);
        Tso->write(jd.toJson());
    });
    connect(Ap,&addpeople::addpeopleItem,this,[=](QString addedaccount,QString extrames){
        QJsonObject jo;
        jo.insert("datatype","addpeople");
        jo.insert("addingaccount",Account);
        jo.insert("addedaccount",addedaccount);
        jo.insert("extrames",extrames);
        QJsonDocument jd(jo);
        Tso->write(jd.toJson());
    });
    connect(priinfo,&privateinfo::renewprivateinfo,this,[=](QString name,QString image,QString personalsig){
        //更新ui及个人数据
        Name=name;
        qDebug()<<name;
        HeadImagePath=image;
        HeadImage.load(HeadImagePath);
        Personalsign=personalsig;
        ui->headimage->setIcon(QPixmap::fromImage(HeadImage));
        QString str=QString("update peopleinfo set name=:name,headimage=:image,personalsign=:sign where account=:account");
        sq->prepare(str);
        sq->bindValue(":name",Name);
        sq->bindValue(":image",HeadImagePath);
        sq->bindValue(":sign",Personalsign);
        sq->bindValue(":account",Account);
        if(!sq->exec())
            qDebug()<<"update private data failed";

    });
    connect(nfl,&newfriendlist::addfriendresult,this,[=](bool result,QString account,QString image,QString name){
        qDebug()<<"widget54:confirmaddfriendresult";
        if(!result)
            return;
        else
        {
            //更新ui
            peopleitem* pi=new peopleitem(ui->peopleitemlist);
            pi->init(name,image,account,"");
            QListWidgetItem* li=new QListWidgetItem(ui->peopleitemlist);
            li->setSizeHint(QSize(ui->peopleitemlist->width(),68));
            ui->peopleitemlist->setItemWidget(li,pi);
            //再构造一个peopleitem加入到peopleitems_account中去
            peopleitem* pi1=new peopleitem(this);
            pi1->init(name,image,account,"");
            Peopleitems_account[account]=pi1;
            Peopleitems_row[nextpeopleitemrow++]=pi1;

            //向服务端发送成功申请消息，让对端也添加该用户
            QJsonObject jo;
            jo.insert("datatype","agreeaddpeople");
            jo.insert("senderaccount",Account);
            jo.insert("receiveraccount",account);
            jo.insert("sendername",Name);
            jo.insert("senderimage",HeadImagePath);
            QJsonDocument jd(jo);
            Tso->write(jd.toJson());

        }
    });
    connect(Tso,&QTcpSocket::readyRead,this,[=](){
        Sleep(75);
        if(newjo)
        {
            QString dt=loginjo.value("datatype").toString(); //分析数据类型
            if(dt=="returnsearchpeople")
            {
                bool exist=loginjo.value("exist").toBool();
                if(exist)
                {
                    Ap->peopleexist=true;
                    QString name=loginjo.value("name").toString();
                    QString image=loginjo.value("image").toString();
                    qDebug()<<"name:"<<name<<" image:"<<image;
                    Ap->name=name;
                    Ap->image=image;
                }
                else
                {
                    Ap->peopleexist=false;
                    Ap->name.clear();
                    Ap->image.clear();
                }
            }
            else if(dt=="returnaddpeople")
            {
                qDebug()<<Name<<" :returnaddpeople";
                QString name=loginjo.value("name").toString();
                QString image=loginjo.value("image").toString();
                QString account=loginjo.value("account").toString();
                QString extrames=loginjo.value("extrames").toString();
                qDebug()<<name<<" "<<image<<" "<<account<<" "<<extrames;
                //更新新朋友添加消息列表
                newfrienditem* ni=new newfrienditem(nfl);
                ni->init(account,image,name,extrames);
                ni->hide();
                nfl->newfriends[account]=ni;
                nfl->newfriendsbyrow[nfl->nextnewfrientrow]=account;
                nfl->nextnewfrientrow++;
                nfl->renewed=true;


            }
            else if(dt=="despatchmes")
            {
                QString senderaccount=loginjo.value("senderaccount").toString();
                QString condendtype=loginjo.value("condendtype").toString();
                QString condend=loginjo.value("condend").toString();
                QString time=loginjo.value("time").toString();
                QString image=loginjo.value("image").toString();
                QString sender=Peopleitems_account[senderaccount]->Name;
                qDebug()<<time<<" "<<sender;
                sendmesitem* si=new sendmesitem(this);
                si->init(senderaccount,Account,sender,image,time,condend,false);
                Peopleitems_account[senderaccount]->HistorySendMes.push_back(si);
                //存储到数据库
                {
                    QString str1="insert into account"+Account+"mes(senderaccount receiveraccount time contend)"+"values(?,?,?,?)";
                    QString str2="insert into account"+senderaccount+"mes(senderaccount receiveraccount time contend)"+"values(?,?,?,?)";
                    sq->prepare(str1);
                    sq->bindValue(0,senderaccount);
                    sq->bindValue(1,Account);
                    sq->bindValue(2,time);
                    sq->bindValue(3,condend);
                    if(!sq->exec(str1))
                        qDebug()<<"widget181:insert failed";
                    sq->bindValue(0,senderaccount);
                    sq->bindValue(1,Account);
                    sq->bindValue(2,time);
                    sq->bindValue(3,condend);
                    if(!sq->exec(str2))
                        qDebug()<<"widget186:insert failed";
                }
                //更改最后一条消息
                Peopleitems_account[senderaccount]->Lastmes=condend;
                Peopleitems_account[senderaccount]->Lastmeschange=true;
                //更新ui
                sendmesitem* rep_si=new sendmesitem(ui->meslist);
                si->init(senderaccount,Account,sender,image,time,condend,false);
                QListWidgetItem* li=new QListWidgetItem(ui->meslist);
                int wordnum=condend.size();
                if(wordnum<=32)
                    li->setSizeHint(QSize(ui->meslist->width(),100));
                else
                {
                    int row=wordnum/27;
                    li->setSizeHint(QSize(ui->meslist->width(),100+40*row));
                }
                ui->meslist->setItemWidget(li,rep_si);
                ui->meslist->update();
                if(Curpeoitem&&Curpeoitem==Peopleitems_account[senderaccount])  //发送时刚好也是当前用户滑动到最低部
                    ui->meslist->scrollToBottom();



            }
            else if(dt=="successaddpeople")
            {
                QString name=loginjo.value("name").toString();
                QString image=loginjo.value("image").toString();
                QString account=loginjo.value("account").toString();
                //更新ui
                peopleitem* pi=new peopleitem(ui->peopleitemlist);
                pi->init(name,image,account,"");
                QListWidgetItem* li=new QListWidgetItem(ui->peopleitemlist);
                li->setSizeHint(QSize(ui->peopleitemlist->width(),68));
                li->setText(QString::number(nextpeopleitemrow));
                ui->peopleitemlist->setItemWidget(li,pi);
                //再构造一个peopleitem加入到peopleitems_account中去
                peopleitem* pi1=new peopleitem(this);
                pi1->init(name,image,account,"");
                Peopleitems_account[account]=pi1;
                qDebug()<<"addpeople:"<<account;
                Peopleitems_row[nextpeopleitemrow++]=pi1;
                //存储到数据库中去
                QString str="insert into account"+Account+"friend"+"(account) values("+account+")";
                QString str1="insert into account"+account+"friend"+"(account) values("+Account+")";
                if(!sq->exec(str))
                    qDebug()<<"widget213:insert failed";
                if(!sq->exec(str1))
                    qDebug()<<"widget216:insert failed";
            }

        }
        newjo=false;
    });
}

void widget::loaddata()
{
    QString table_people="account"+Account+"friend";
    qDebug()<<table_people;
    QString st="select * from "+table_people;
    if(!sq->exec(st))
        qDebug()<<"widget219 select failed";
    QSqlQuery sql;
    while(sq->next())
    {
        QString friendaccount=sq->value("account").toString();
        QString str="select * from peopleinfo where account="+friendaccount+";";
        if(!sql.exec(str))
            qDebug()<<"widget225 select failed";
        while(sql.next())
        {
            QString name=sql.value("name").toString();
            QString image=sql.value("headimage").toString();
            QString personalsign=sql.value("personalsign").toString();
            QString lastmes=sql.value("lastmes").toString();
            peopleitem* pi=new peopleitem;
            pi->init(name,image,friendaccount,lastmes);
            Peopleitems_account[friendaccount]=pi;
            Peopleitems_row[nextpeopleitemrow++]=pi;
            peopleitem* pi1=new peopleitem(ui->peopleitemlist);
            pi1->init(name,image,friendaccount,lastmes);
            QListWidgetItem* li=new QListWidgetItem(ui->peopleitemlist);
            li->setSizeHint(QSize(ui->peopleitemlist->width(),68));
            ui->peopleitemlist->setItemWidget(li,pi1);
        }

    }
    //更新历史消息
    QString table="account"+Account+"mes";
    QString str=QString("select * from %1").arg(table);
    if(!sq->exec(str))
        qDebug()<<"更新历史消息失败";
    while(sq->next())
    {
        QString senderaccount=sq->value("senderaccount").toString();
        QString receiveraccount=sq->value("receiveraccount").toString();
        QString time=sq->value("time").toString();
        QString contend=sq->value("contend").toString();

        bool own=false;
        if(senderaccount==Account)
            own=true;
        sendmesitem* si=new sendmesitem;
        if(senderaccount!=Account)
        {
            si->init(senderaccount,receiveraccount,Peopleitems_account[senderaccount]->Name,Peopleitems_account[senderaccount]->HeadImage,time,contend,own);

        }

        else
        {
            si->init(senderaccount,receiveraccount,Name,HeadImagePath,time,contend,own);

        }

        if(Peopleitems_account[receiveraccount]==nullptr)
            qDebug()<<"266";
        else
            Peopleitems_account[receiveraccount]->HistorySendMes.push_back(si);
    }
    // for(int i=0;i<mesnum;i++)
    // {
    //     QString mes= jo.value(QString("mes%1").arg(QString::number(i))).toString();
    //     QStringList strl=mes.split(";",Qt::SkipEmptyParts);
    //     QHash<QString,QString> meshash;
    //     for(QString&e:strl)
    //     {
    //         QStringList str=e.split(":");
    //         QString key=str.at(0);
    //         QString value=str.at(1);
    //         meshash[key]=value;
    //     }
    //     QString sender=meshash["senderaccount"];
    //     QString receiver=meshash["receiveraccount"];
    //     QString time=meshash["time"];
    //     QString contend=meshash["contend"];
    //     bool own;
    //     if(sender==Account)
    //         own=true;
    //     else
    //         own=false;
    //     sendmesitem* si=new sendmesitem;
    //     si->init(sender,receiver,Peopleitems_account[sender]->Name,Peopleitems_account[sender]->HeadImage,time,contend,own);
    //     Peopleitems_account[receiver]->HistorySendMes.push_back(si);
}

void widget::renewinfo()
{
    QJsonObject sendjo;
    sendjo.insert("datatype","askrenewinfo");
    //个人信息
    sendjo.insert("account",Account);
    sendjo.insert("image",HeadImagePath);
    sendjo.insert("name",Name);
    sendjo.insert("personalsing",Personalsign);

    int friendnum=Peopleitems_account.size();
    sendjo.insert("friendnum",friendnum);
    int num=0;
    int mesnum=0;
    foreach (const QString &key, Peopleitems_account.keys())
    {
        //好友列表
        QString fre="friend"+QString::number(num)+"account";
        sendjo.insert(fre,key);
        //消息列表
        for(auto&e:Peopleitems_account[key]->HistorySendMes)
        {
            QString men="mes"+QString::number(mesnum);
            QString senderaccount=e->senderaccount;
            QString receiveraccount=e->receiveraccount;
            QString time=e->time;
            QString contend=e->mes;
            QString str=QString("senderaccount:%1;receiveraccount:%2;time:%3;contend:%4;").arg(senderaccount).arg(receiveraccount).arg(time).arg(contend);
            sendjo.insert(men,str);
            mesnum++;
        }
        num++;
    }
    sendjo.insert("mesnum",mesnum);
    QJsonDocument sendjd(sendjo);
    Tso->write(sendjd.toJson());
}



void widget::on_sendmesbtn_clicked()
{

    QString mes=ui->SendMesEdit->toPlainText();
    QString time=QTime::currentTime().toString();
    QString image=HeadImagePath;
    QString Sendeaccount=Account;
    QString sender=Name;
    QString receiveraccount=Curpeoitem->Account;
    QString contendtype="QString";
    QVariant contend=mes;
    //添加到数据库中
    QString str1=QString("insert into account%1mes (senderaccount,receiveraccount,time,contend) values(?,?,?,?);").arg(Account);
    QString str2=QString("insert into account%1mes (senderaccount,receiveraccount,time,contend) values(?,?,?,?);").arg(receiveraccount);
    sq->prepare(str1);
    sq->bindValue(0,Account);
    sq->bindValue(1,receiveraccount);
    sq->bindValue(2,time);
    sq->bindValue(3,contend);
    sq->exec();
    sq->prepare(str2);
    sq->bindValue(0,Account);
    sq->bindValue(1,receiveraccount);
    sq->bindValue(2,time);
    sq->bindValue(3,contend);
    sq->exec();
    QJsonObject jo;
    jo.insert("datatype","sendmes");
    jo.insert("senderaccount",Sendeaccount);
    jo.insert("receiveraccount",receiveraccount);
    jo.insert("image",image);
    jo.insert("sender",sender);
    jo.insert("condendtype",contendtype);
    jo.insert("condend",contend.toString());
    jo.insert("time",time);
    QJsonDocument jd(jo);
    Tso->write(jd.toJson());
    //更改最后一条消息
    //更新ui
    sendmesitem* si=new sendmesitem(ui->meslist);
    si->init(Account,Curpeoitem->Account,sender,image,time,mes,true);
    QListWidgetItem* li=new QListWidgetItem(ui->meslist);
    int wordnum=mes.size();
    if(wordnum<=27)
        li->setSizeHint(QSize(ui->meslist->width(),100));
    else
    {
        int row=wordnum/27;
        li->setSizeHint(QSize(ui->meslist->width(),100+40*row));
    }
    ui->meslist->setItemWidget(li,si);
    ui->meslist->scrollToBottom();
    //更新用户信息
    if(Curpeoitem!=nullptr)
    {
        sendmesitem* si=new sendmesitem;
        si->init(Account,Curpeoitem->Account,sender,image,time,mes,true);
        //加入历史消息集
        Curpeoitem->HistorySendMes.push_back(si);
        //更改最后一条消息
        Curpeoitem->Lastmes=mes;
        Curpeoitem->Lastmeschange=true;
    }

}

void widget::on_addpeoplebtn_clicked()
{
    Ap->move(250,100);
    Ap->show();
}

void widget::on_SendMesEdit_textChanged()
{
    if(ui->SendMesEdit->toPlainText().isEmpty())
        ui->sendmesbtn->setEnabled(false);
    else
        ui->sendmesbtn->setEnabled(true);
}


void widget::on_peopleitemlist_currentRowChanged(int currentRow)
{
    ui->meslist->clear();
    Curpeoitem=Peopleitems_row[currentRow];
    if(Curpeoitem==nullptr)
        return;
    //切换当前用户更新ui->meslist
    for(int i=0;i<Curpeoitem->HistorySendMes.size();i++)
    {
        sendmesitem* si=Curpeoitem->HistorySendMes.at(i);
        sendmesitem* resi=new sendmesitem(ui->meslist);
        resi->init(si->senderaccount,si->receiveraccount,si->name,si->image,si->time,si->mes,si->own);
        QListWidgetItem* li=new QListWidgetItem(ui->meslist);
        li->setSizeHint(QSize(ui->meslist->width(),100));
        ui->meslist->setItemWidget(li,resi);
    }
    ui->meslist->scrollToBottom();
}


void widget::on_newpeople_clicked()
{
    nfl->move(200,150);
    nfl->show();
}


void widget::on_headimage_clicked()
{
    priinfo->move(100,100);
    priinfo->show();
}


void widget::on_peopleitemlist_itemDoubleClicked(QListWidgetItem *item)
{
    //查看好友信息
    int row=item->text().toInt();
    peopleitem* it=Peopleitems_row[row];
    otherinfo->init(it->Name,it->HeadImage,otherinfo->personalsign,false);
    otherinfo->show();

}

